package org.cb.gui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileFilter;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import org.cb.core.CBClassFilter;

/**
 * 
 * @author Fsig
 * 
 * A basic GUI to select a script.
 * 
 * This will need to work hand in hand with the
 * class loader, to load in the scripts and their
 * details, and then to launch the script.
 *
 */
public class ScriptLauncher extends JFrame implements ActionListener{
	
	private static final long serialVersionUID = 1L;
	private JTable scriptTable = new JTable();
	private JButton b = new JButton("Start selected script");
	
	private static FileFilter filter = new CBClassFilter();
	
	/**
	 * Test information...
	 * 
	 * This information will need to be loaded dynamically.
	 */
	String[] scriptNames = {"Script name", "Description", "Version", "Author"};
	Object[][] scriptData;
	
	public ScriptLauncher(File dir){
		this.setTitle("CB | Script Chooser");
		this.setSize(700, 200);
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		this.setAlwaysOnTop(true);
		
		scriptData = null;
		scriptData = new Object[countClasses(dir)][4];
		findClasses(dir);
		
		scriptTable = new JTable(scriptData, scriptNames);
		JScrollPane scrollPane = new JScrollPane(scriptTable);
		
		b.addActionListener(this);
		
		add(scrollPane, BorderLayout.CENTER);
		add(b, BorderLayout.SOUTH);
		
		this.setVisible(true);
	}
	
	/**
	 * Count the classes.
	 * 
	 * @param dir
	 * @return int
	 */
	private int countClasses(File dir){
		int count = 0;
		 for (File f : dir.listFiles(filter)) {
            if(!f.isDirectory())
            	count++;
		 }
		 return count;
	}
	
	/**
	 * Find the classes and add them to the object.
	 * 
	 * @param dir
	 */
	private void findClasses(File dir){
		int count = 0;
		
		 for (File f : dir.listFiles(filter)) {
             if(!f.isDirectory()){
            	 String className = f.getName().substring(0, f.getName().indexOf("."));
            	 scriptData[count][0] = className; 
            	 
            	 try{		 
            	     /*for(Field i: c.getDeclaredFields()) {
            	    	 System.out.println("Field name" + i.getName());
            	     }*/
            	 }catch(Exception e){e.printStackTrace();}
            	 /**
            	  * We need to work out how to reflect some fields
            	  * to get the description, version and author.
            	  */
            	 
            	 count++;
             }
		 }
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == b){
			MainGUI.startScript(scriptTable.getValueAt(scriptTable.getSelectedRow(), 0).toString());
		}	
	}

}
